class User < ApplicationRecord
  has_secure_password

  mount_uploader :avatar, BaseUploader

  enum sex: [:male, :female]

  enum state: [:pending, :agree, :disagree]

  validates :phone, presence: true, uniqueness: true
  
  has_many :addresses, dependent: :destroy
  has_many :orders
  has_many :order_items
  has_many :favorites, dependent: :destroy
  has_many :favorite_spus, -> { where favoriteable_type: "Spu" }, class_name: "Favorite"
  has_many :favorite_shops, -> { where favoriteable_type: "Shop" }, class_name: "Favorite"
  has_many :favorite_brands, -> { where favoriteable_type: "Brand" }, class_name: "Favorite"
  has_many :carts, -> { where on_cart: true }, class_name: "OrderItem"
  has_many :comments
  has_many :user_search_keys, dependent: :destroy
  has_many :spu_tracks, dependent: :destroy
  has_many :user_coupons, dependent: :destroy
  has_many :coupons, through: :user_coupons
  has_many :notifications
  has_many :shop_chats, dependent: :destroy
  has_many :chat_shops, through: :shop_chats
  has_many :feedbacks, dependent: :destroy
  has_many :deposits
  has_many :chat_messages, class_name: 'ChatMessage', as: :commentable
  has_many :topics
  has_many :user_scratch_card_awards, dependent: :destroy
  has_many :scratch_card_awards, through: :user_scratch_card_awards
  has_many :bonus_records
  
  belongs_to :parent, class_name: 'User', foreign_key: 'parent_id', optional: true
  belongs_to :membership, optional: true

  has_one :default_address, -> {where is_default: true}, class_name: 'Address'
  has_one :shop

  def coupon_had(coupon)
    user_coupon = self.user_coupons.where(coupon_id: coupon.id, state: :unused).first
    !user_coupon.blank?
  end

  def computed_price price
    if self.membership.blank?
      price
    else
      price * self.membership.discount / 100
    end
  end
  
end
